"""
全局日志配置
"""
import logging
import logging.config
import os
from pathlib import Path
from config.settings import settings


def setup_logging():
    """设置全局日志配置"""
    log_level = settings.get("logging.level", "INFO")
    log_format = settings.get("logging.format", "%(asctime)s - %(name)s - %(levelname)s - %(message)s")
    log_file = settings.get("logging.file", "logs/app.log")
    
    # 确保日志目录存在
    log_dir = Path(log_file).parent
    log_dir.mkdir(parents=True, exist_ok=True)
    
    # 日志配置字典
    logging_config = {
        "version": 1,
        "disable_existing_loggers": False,
        "formatters": {
            "standard": {
                "format": log_format,
                "datefmt": "%Y-%m-%d %H:%M:%S"
            },
            "detailed": {
                "format": "%(asctime)s - %(name)s - %(levelname)s - %(filename)s:%(lineno)d - %(message)s",
                "datefmt": "%Y-%m-%d %H:%M:%S"
            }
        },
        "handlers": {
            "console": {
                "class": "logging.StreamHandler",
                "level": log_level,
                "formatter": "standard",
                "stream": "ext://sys.stdout"
            },
            "file": {
                "class": "logging.handlers.RotatingFileHandler",
                "level": log_level,
                "formatter": "detailed",
                "filename": log_file,
                "maxBytes": 10485760,  # 10MB
                "backupCount": 5,
                "encoding": "utf8"
            },
            "error_file": {
                "class": "logging.handlers.RotatingFileHandler",
                "level": "ERROR",
                "formatter": "detailed",
                "filename": "logs/error.log",
                "maxBytes": 10485760,  # 10MB
                "backupCount": 5,
                "encoding": "utf8"
            }
        },
        "loggers": {
            "": {  # 根日志器
                "handlers": ["console", "file", "error_file"],
                "level": log_level,
                "propagate": False
            },
            "api": {
                "handlers": ["console", "file"],
                "level": log_level,
                "propagate": False
            },
            "tests": {
                "handlers": ["console"],
                "level": log_level,
                "propagate": False
            }
        }
    }
    
    # 应用配置
    logging.config.dictConfig(logging_config)
    
    # 设置第三方库的日志级别
    logging.getLogger("urllib3").setLevel(logging.WARNING)
    logging.getLogger("httpx").setLevel(logging.WARNING)
    logging.getLogger("asyncio").setLevel(logging.WARNING)


def get_logger(name: str) -> logging.Logger:
    """获取指定名称的日志器"""
    return logging.getLogger(name)


# 全局日志器
logger = get_logger(__name__)


class LoggingMixin:
    """日志混入类，为其他类提供日志功能"""
    
    @property
    def logger(self) -> logging.Logger:
        """获取类的日志器"""
        if not hasattr(self, '_logger'):
            self._logger = get_logger(self.__class__.__name__)
        return self._logger


# 初始化日志配置
setup_logging()